function trim(target) {
	return target.replace(/^\s+|\s+$/g,"");
}

var sel = window.getSelection();
var range = sel.getRangeAt(0);
var word=trim(range.toString());

function onSuggestion(data) {
	if (data) {
		if ('suggestions' in data) {
			var word=data.suggestions[0];
			chrome.extension.sendRequest({'action' : 'suggestion', 'word': word}, onSuggestion);
		}
		else {
			chrome.extension.sendRequest({'action' : 'query', 'word': data.word}, onText);
		}
	}
};
function onText(data) {
	if (data) {
		var raw="(UNDEFINED)";
		if (0 < data.length) {
			raw = data[0].raw;
		}

		var newTextNode = document.createTextNode(raw);
		range.insertNode(newTextNode);
		range.setStartAfter(newTextNode);
		sel.removeAllRanges();
		sel.addRange(range);
	}
};

chrome.extension.sendRequest({'action' : 'suggestion', 'word': word}, onSuggestion);

